<?php

namespace plugins\assets\controller;

use app\controller\backend\BaseController;
use app\exception\ModelException;
use plugins\assets\model\AssetsCopyright;
use plugins\assets\model\AssetsCopyrightDetail;
use plugins\assets\validate\AssetsCopyrightValidate;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;

class CopyrightController extends BaseController
{

    /**
     * 列表
     * @return \think\response\Json
     * @throws ModelException
     */
    public function index()
    {
        $status = $this->request->param("status/d", 0);//1未开始 2生效中 3已过期
        $type = $this->request->param("type/d", 0);//素材类型 1图片2音频3视频4字体
        $limit = $this->request->param("limit/d", 10);
        $material_name = $this->request->param("material_name/s", ""); //
        $where[] = ['d.seller_id', "=", $this->admin['seller_id']];
        if ($type > 0) {
            $where[] = ["d.type", "=", $type];
        }
        $time = date("Y-m-d");
        if ($status == 1) {
            $where[] = ["c.begin_time", ">", $time];
        } elseif ($status == 2) {
            $where[] = ["c.begin_time", "<=", $time];
            $where[] = ["c.end_time", ">=", $time];
        } elseif ($status == 3) {
            $where[] = ["c.end_time", "<", $time];
        }
        if(!empty($material_name)){
            $where[] = ["d.material_name", "like", "%{$material_name}%"];
        }
        $AssetsCopyrightDetailModel = new AssetsCopyrightDetail();
        $list = $AssetsCopyrightDetailModel->getListWithCopyright($where, $limit);
        return json(pageReturn($list));
    }

    /**
     * 添加版权管理
     * @return \think\response\Json
     * @throws ModelException
     */
    public function add()
    {
        $param = $this->request->post(['type', 'subject', 'supplier_name', 'begin_time', 'end_time',
            'price', 'doc_no', 'files', 'use_range', 'material_type', 'material_detail']);
        $this->validateData($param, "add");
        $param['end_time'] = !empty($param['end_time']) ? $param['end_time'] : "2999-12-31";
        $detail = $this->checkMaterialDetail($param, $this->admin['seller_id']);
        $param['files'] = !empty($param['files'])?(is_array($param['files']) ? implode(",", $param['files']) : $param['files']):"";
        unset($param['material_detail']);
        $model = new AssetsCopyright();
        Db::startTrans();
        try {
            $param['seller_id'] = $this->admin['seller_id'];
            $param['apply_id'] = $this->admin['uid'];
            $param['apply_user'] = $this->admin['name'];
            $res = $model->add($param);
            foreach ($detail as $k => $v) {
                $detail[$k]['copyright_id'] = $res['data'];
            }
            (new AssetsCopyrightDetail())->insertAll($detail);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return jsonReturn(-1, $e->getMessage());
        }
        return json($res);
    }

    /**
     * 详情
     * @throws ModelException
     */
    public function getInfo()
    {
        $copyright_id = $this->request->param("copyright_id/d", 0); //版权的id
        $model = new AssetsCopyright();
        $info = $model->getInfo(['id' => $copyright_id, 'seller_id' => $this->admin['seller_id']])['data'];
        if (empty($info)) {
            return jsonReturn(-1, lang("内容不存在"));
        }
        $time = date("Y-m-d");
        if ($info['begin_time'] > $time) {
            $info['status_text'] = lang("未开始");
        } elseif ($info['end_time'] < $time) {
            $info['status_text'] = lang("已过期");
        } else {
            $info['status_text'] = lang("生效中");
        }
        $info["files"] = !empty($info['files'])?explode(",",$info['files']):[];
        $AssetsCopyrightDetailModel = new AssetsCopyrightDetail();
        $detail = $AssetsCopyrightDetailModel->getListNoLimit(['copyright_id' => $copyright_id], '', 'detail_id desc')['data'];
        return jsonReturn(0, lang('查询成功'), ['info' => $info, "detail" => $detail]);
    }

    /**
     * @return \think\response\Json
     * @throws ModelException
     */
    public function edit()
    {
        $param = $this->request->post(['id', 'type', 'subject', 'supplier_name', 'begin_time', 'end_time',
            'price', 'doc_no', 'files', 'use_range', 'material_type', 'material_detail']);
        $this->validateData($param, "update");
        $param['end_time'] = !empty($param['end_time']) ? $param['end_time'] : "2999-12-31";
        $detail = $this->checkMaterialDetail($param, $this->admin['seller_id']);
        $param['files'] = !empty($param['files'])?(is_array($param['files']) ? implode(",", $param['files']) : $param['files']):"";
        unset($param['material_detail']);

        //验证内容存不存在
        $model = new AssetsCopyright();
        $where['id'] = $param['id'];
        $where['seller_id'] = $this->admin['seller_id'];
        $info = $model->getInfo($where, "", "id")['data'];
        if (empty($info)) {
            return jsonReturn(-2, lang("内容不存在"));
        }
        $AssetsCopyrightDetailModel = new AssetsCopyrightDetail();
        Db::startTrans();
        try {
            $model->edit($where, $param);
            $AssetsCopyrightDetailModel->where(['copyright_id' => $param['id']])->delete();
            $AssetsCopyrightDetailModel->insertAll($detail);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return jsonReturn(-3, $e->getMessage());
        }
        return jsonReturn(0, lang('操作成功'));
    }

    public function del()
    {
        $param = $this->request->only(['detail_id']);
        if (empty($param['detail_id'])) {
            return jsonReturn(-1, lang("参数错误"));
        }
        $detailId = [];
        foreach ($param['detail_id'] as $k => $v) {
            $detailId[] = intval($v);
        }
        $AssetsCopyrightDetailModel = new AssetsCopyrightDetail();
        $res = $AssetsCopyrightDetailModel->where([['detail_id', "in", $detailId],
            ['seller_id', '=', $this->admin['seller_id']]])->delete();
        if ($res) {
            return jsonReturn(0, lang('删除成功'));
        }
        return jsonReturn(-1, lang('删除失败'));
    }

    /**
     * 验证字段的内容
     * @param $param
     * @param string $scene
     * @throws ModelException
     */
    private function validateData($param, $scene = "")
    {
        try {
            validate(AssetsCopyrightValidate::class)->scene($scene)->check($param);
        } catch (ValidateException $e) {
            throw new ModelException($e->getMessage(), $e->getCode() > 0 ? $e->getCode() : -1);
        }
    }

    /**
     * 验证素材信息的内容
     * @param $param
     * @param $sellerId
     * @return array
     * @throws ModelException
     */
    private function checkMaterialDetail($param, $sellerId)
    {
        $materialDetail = is_string($param['material_detail']) ? json_decode($param['material_detail'], true) : $param['material_detail'];
        if (empty($materialDetail)) {
            throw new ModelException(lang("素材内容错误"), -2);
        }
        $detail = [];
        foreach ($materialDetail as $k => $v) {
            $detail[$k]['material_type'] = $v['material_type'] = $param['material_type'];
            $detail[$k]['type'] = $v['type'] = $param['type'];
            $detail[$k]['category'] = $v['category'] = 1;
            $detail[$k]['copyright_id'] = !empty($param['id']) ? $param['id'] : 0;
            $this->validateData($v, "purchase");
            $detail[$k]['material_no'] = !empty($v['material_no'])?$v['material_no']:"";
            $detail[$k]['material_name'] = $v['material_name'];
            $detail[$k]['material_link'] = $v['material_link'];
            $detail[$k]['material_cover'] = !empty($v['material_cover'])?$v['material_cover']:"";
            $detail[$k]['material_url'] = $v['material_url'];
            $detail[$k]['seller_id'] = $sellerId;
            $detail[$k]['create_time'] = date("Y-m-d H:i:s");
        }
        return $detail;
    }

}